#include "memory_info.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int GetMemoryInfo(struct MemoryInfo *info) {
    if (!info) return -1;
    FILE *file = fopen("/proc/meminfo", "r");
    if (file == NULL) {
        perror("fopen /proc/meminfo");
        return -1;
    }

    memset(info, 0, sizeof(struct MemoryInfo));

    char line[256];
    while (fgets(line, sizeof(line), file) != NULL) {
        if        (sscanf(line, "MemTotal: %u kB\n", &info->mem_total) == 1) {
            continue;
        } else if (sscanf(line, "MemFree: %u kB\n", &info->mem_free) == 1) {
            continue;
        } else if (sscanf(line, "Buffers: %u kB\n", &info->mem_buffers) == 1) {
            continue;
        } else if (sscanf(line, "Cached: %u kB\n", &info->mem_cached) == 1) {
            continue;
        } else if (sscanf(line, "MemAvailable: %u kB\n", &info->mem_avalible) == 1) {
            continue;
        } else if (sscanf(line, "SwapTotal: %u kB\n", &info->swap_total) == 1) {
            continue;
        } else if (sscanf(line, "SwapFree: %u kB\n", &info->swap_free) == 1) {
            continue;
        }
    }

    fclose(file);
    return 0;
}
